package xyz.bali16.module.person.information.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gitee.starblues.bootstrap.annotation.AutowiredType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import xyz.bali16.application.core.enums.ApiEnum;
import xyz.bali16.application.core.model.Result;
import xyz.bali16.module.person.information.entity.Information;
import xyz.bali16.module.person.information.entity.UserInformation;
import xyz.bali16.module.person.information.model.InformationAddParam;
import xyz.bali16.module.person.information.model.InformationUpdateParam;
import xyz.bali16.module.person.information.service.UserInformationService;
import xyz.bali16.module.person.information.utils.ResultUtils;
import xyz.bali16.module.person.information.service.InformationService;

import javax.validation.Valid;
import java.util.List;

import static xyz.bali16.application.core.model.Result.*;
import static xyz.bali16.application.core.model.Result.failure;

/**
 * @author bali2 on 9/3/2023.
 * @version 1.0
 */
@RestController
@RequestMapping(BaseController.API + "information")
@Api(tags = "个人信息接口")
@AllArgsConstructor

public class InformationController extends BaseController {
    public static final Logger logger = LoggerFactory.getLogger(InformationController.class);
    @Autowired
    InformationService informationService;
    @Autowired
    @AutowiredType(AutowiredType.Type.PLUGIN_MAIN)
    UserInformationService userInformationService;

    @GetMapping
    //@PreAuthorize("@auth.permission('plugin:information:query')")
    @ApiOperation(value = "查询个人信息列表")
    public Result<List<Information>> getInformationList() {
        return success(ApiEnum.GET_SUCCESS, informationService.list());
    }

    @GetMapping("/{userId}")
    @ApiOperation("获取个人信息")
    @ApiImplicitParam(name = "userId", value = "用户id", paramType = "path", required = true)
    //@PreAuthorize("@auth.permission('plugin:information:query')")
    public Result<Information> getInformation(@PathVariable("userId") String userId) {
        try {
            UserInformation userInformation = userInformationService.getByUserId(userId);
            if (userInformation != null) {
                Information information = informationService.getById(userInformation.getInformationId());
                return success(ApiEnum.GET_SUCCESS, information);
            }
        } catch (Exception e) {
            ResultUtils.errorLog(logger, e, "获取个人信息 '{}' 失败. {}", userId, e.getMessage());
            return failure(ApiEnum.GET_ERROR, e);
        }
        return failure(String.valueOf(ApiEnum.GET_ERROR));
    }

    @PostMapping
    @ApiOperation("添加个人信息")
    //@PreAuthorize("@auth.permission('plugin:information:add')")
    public Result<String> add(@RequestBody @Valid InformationAddParam param) {
        try {
            UserInformation userInformation = userInformationService.getByUserId(param.getUserId());
            if (userInformation == null) {
                informationService.addInformation(param);
                return response(ApiEnum.ADD_SUCCESS);
            }
        } catch (Exception e) {
            ResultUtils.errorLog(logger, e, "新增个人信息信息失败 {}", e.getMessage());
            return failure(ApiEnum.ADD_ERROR, "新增个人信息失败", e);
        }
        return failure(String.valueOf(ApiEnum.ADD_ERROR));
    }

    @PutMapping
    @ApiOperation("修改个人信息")
    //@PreAuthorize("@auth.permission('plugin:information:update')")
    public Result<String> update(@RequestBody @Valid InformationAddParam param) {
        try {
            informationService.updateInformation(param);
            return response(ApiEnum.UPDATE_SUCCESS);
        } catch (Exception e) {
            ResultUtils.errorLog(logger, e, "更新个人信息 '{}' 信息失败 {}", param.getUserId(), e.getMessage());
            return failure(ApiEnum.UPDATE_ERROR, "更新个人信息失败", e);
        }
    }

    @DeleteMapping("/{userId}")
    @ApiOperation("删除个人信息")
    @ApiImplicitParam(name = "userId", value = "个人信息id", paramType = "path", required = true)
    @Transactional
    //@PreAuthorize("@auth.permission('plugin:information:delete')")
    public Result<String> deleteInformation(@PathVariable("userId") String userId) {
        try {
            UserInformation userInformation = userInformationService.getByUserId(userId);
            informationService.delete(userInformation.getInformationId());
            userInformationService.removeByUserId(userId);
            return response(ApiEnum.DELETE_SUCCESS);
        } catch (Exception e) {
            ResultUtils.errorLog(logger, e, "删除个人信息 '{}' 失败. {}", userId, e.getMessage());
            return failure(ApiEnum.DELETE_ERROR, e);
        }
    }

}
